from flask import request, session
from flask_restful import Resource

from database import Database


# Mock user database
class updateAccount(Resource):
    def post(self):
        db = Database()
        type = session.get('type')
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        user_type = data.get('type')
        borrowLimit = data.get('borrowLimit')
        first_name = data.get('firstName')
        last_name = data.get('lastName')
        email = data.get('email')
        address = data.get('address')
        image = data.get('imageUrl')
        if type == 'user':
            user = db.execute_query("SELECT * FROM useraccount WHERE userId = %s", (username,))
            if user is None or user[0] == username:
                db.execute_query(
                    "UPDATE useraccount SET userId=%s, type=%s, borrowLimit=%s, password=%s, firstName=%s, lastName=%s, email=%s, address=%s, imageUrl=%s WHERE userId=%s",
                    (
                        username, user_type, borrowLimit, password, first_name, last_name, email, address, image,
                        username))
                print(username)
                print(password)
                return {"message": "user update successfully"}, 200
            else:
                return {"message": "user already exists"}, 200
        elif type == 'manager':
            manager = db.execute_query.execute("SELECT * FROM manageraccount WHERE managerId = %s", (username,))

            if manager is None or manager[0] == username:
                db.execute_query.execute(
                    "UPDATE manageraccount SET userId=?,type=?, borrowLimit=?, password=?, fistName=?, lastName=?, "
                    "email=?, address=?, imageUrl=? WHERE userId=?",
                    (
                        username, user_type, borrowLimit, password, first_name, last_name, email, address, image,
                        username))
                return {"message": "manager update successfully"}, 200
            else:
                return {"message": "user already exists"}, 200
        else:
            return {"message": "please login"}, 200
